package me.helllp.book.concurrent.ch04;

import java.util.concurrent.TimeUnit;

/**
 * 死锁的演示
 * 
 * @author Administrator
 *
 */
public class DeadLock extends Thread{
	private Object tool;
	
	static Object fork1 = new Object();
	static Object fork2 = new Object();
	
	public DeadLock(Object obj) {
		this.tool = obj;
		
		if(obj == fork1){
			this.setName("哲学家1");
		}
		
		if(obj == fork2){
			this.setName("哲学家2");
		}
	}
	
	@Override
	public void run() {
		if(tool == fork1){
			synchronized (fork1) {
				try {
					TimeUnit.SECONDS.sleep(1);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				synchronized (fork2) {
					System.out.println("哲学家1开始吃饭了！");
				}
			}
		}
		
		if(tool == fork2){
			synchronized (fork2) {
				try {
					TimeUnit.SECONDS.sleep(1);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				synchronized (fork1) {
					System.out.println("哲学家2开始吃饭了！");
				}
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		DeadLock a = new DeadLock(fork1);
		DeadLock b = new DeadLock(fork2);
		
		a.start();
		b.start();
		
		TimeUnit.SECONDS.sleep(2);
	}
}
